package com.powerunion.datacollection.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.apache.log4j.Logger;

import com.powerunion.datacollection.common.Constants;
import com.powerunion.datacollection.common.Format;
import com.powerunion.datacollection.common.SystemException;
import com.powerunion.datacollection.dao.CollectionTaskDao;
import com.powerunion.datacollection.dao.DaoException;
import com.powerunion.datacollection.model.CollectionTask;
import com.powerunion.datacollection.model.jsonObject.CollectionTaskJSONObject;
import com.powerunion.datacollection.persistence.db.jdbc.operator.QueryOperator;
import com.powerunion.datacollection.persistence.db.jdbc.operator.RsDataSet;
import com.powerunion.datacollection.persistence.db.jdbc.operator.SqlParameter;
import com.powerunion.datacollection.persistence.db.jdbc.operator.SqlParameterSet;
import com.powerunion.datacollection.persistence.db.jdbc.operator.SqlType;
import com.powerunion.datacollection.persistence.db.jdbc.operator.UpdateOperator;
import com.powerunion.util.log.LogHelper;
import com.powerunion.util.query.jdbc.QueryParameters;

public class CollectionTaskDaoImpl extends JdbcBase implements CollectionTaskDao {
	// 初始化日志类
	private static final Logger logger = LogHelper.getInstance().getLogger(
			CollectionTaskDaoImpl.class);
	
	public boolean delete(String[] codes) {
		if (logger.isDebugEnabled()) {
			logger.debug(Constants.INTOMETHOD + "delete");
		}
		String sql = "delete from dc_workflow_table where id = ? ";
		UpdateOperator update = new UpdateOperator();
		update.setSql(sql);
		
		for(int i=0;i<codes.length;i++) {
			SqlParameterSet spSet = new SqlParameterSet();
			spSet.addParameter(new SqlParameter(SqlType.VARCHAR,codes[i]));
			update.addBatchParameter(spSet);
		}
		
		update.access();
		int[] effectCount = update.getBatchEffectCounts();
		if(effectCount != null && effectCount.length>0) {
			if (logger.isDebugEnabled()) {
				logger.debug("delete:" + Constants.DELETE + "采集任务信息"
						+ Constants.SUCCESS);
			}
			return true;
		}else{
			if (logger.isDebugEnabled()) {
				logger.debug("delete:" + Constants.DELETE + "采集任务信息"
						+ Constants.FAIL);
			}
			return false;
		}
	
	}

	public String save(CollectionTask ct){
		if (logger.isDebugEnabled()) {
			logger.debug(Constants.INTOMETHOD + "save");
		}
		String sql = "";
		String resultId = "";
		if (ct.getId() == null || ct.getId().equals("")) {//新增
			String id = String.valueOf(this.getSeq("dc_workflow_table"));
			ct.setId(id);
			StringBuffer sqlSave = new StringBuffer();
			sqlSave.append("insert into dc_workflow_table (wf_name,wf_desc,wf_type,date_created,crt_user_code,")
				   .append("date_startup,date_completed,wf_instance_num,startUp_role_id,form_id,proc_id,id) ")
				   .append(" values(?,?,?,?,?,?,?,?,?,?,?,?)");
			sql = sqlSave.toString();
		} else {//修改
			StringBuffer sqlUpdate = new StringBuffer();
			sqlUpdate.append("update dc_workflow_table set wf_name =?, wf_desc=?,wf_type=?,date_created=?,crt_user_code=?,")
				   .append(" date_startup =? ,date_completed =?,wf_instance_num = ?,startUp_role_id=?,")
				   .append("form_id=?,proc_id=? where id =?");
			sql = sqlUpdate.toString();
		}
		UpdateOperator update = new UpdateOperator();
		update.setSql(sql);
		update.addParameter(new SqlParameter(SqlType.VARCHAR,ct.getName()));
		update.addParameter(new SqlParameter(SqlType.VARCHAR,ct.getDescription()));
		update.addParameter(new SqlParameter(SqlType.INTEGER,new Integer(ct.getType())));
		update.addParameter(new SqlParameter(SqlType.DATE,new java.sql.Date(ct.getCreateDate().getTime())));
		update.addParameter(new SqlParameter(SqlType.VARCHAR,ct.getCrtUserCode()));
		update.addParameter(new SqlParameter(SqlType.DATE,new java.sql.Date(ct.getStartupDate().getTime())));
		update.addParameter(new SqlParameter(SqlType.DATE,new java.sql.Date(ct.getCompletedDate().getTime())));
		update.addParameter(new SqlParameter(SqlType.INTEGER,new Integer(ct.getInstanceNum())));
		update.addParameter(new SqlParameter(SqlType.VARCHAR,ct.getStartUpRole()));
		update.addParameter(new SqlParameter(SqlType.VARCHAR,ct.getFormId()));
		update.addParameter(new SqlParameter(SqlType.VARCHAR,ct.getProcId()));
		update.addParameter(new SqlParameter(SqlType.VARCHAR,ct.getId()));
		try{
			update.access();
		}catch(Exception e){
			logger.error("保存任务失败,任务id:"+ct.getId()+" 任务名："+ct.getName(), e);
			return "";
		}

		int effectCount = update.getEffectCounts();
		if(effectCount > 0) {
			
			if (logger.isDebugEnabled()) {
				logger.debug("save:" + Constants.SAVE + "采集任务信息"
						+ Constants.SUCCESS);
			}
			resultId = ct.getId();
			return resultId;
		}else{
			if (logger.isDebugEnabled()) {
				logger.debug("save:" + Constants.SAVE + "采集任务信息"
						+ Constants.FAIL);
			}
			return "";
		}
	}
	
	public CollectionTask getBykey(String id) {
		CollectionTask ct = new CollectionTask();
		StringBuffer sql = new StringBuffer();
		sql.append("select d.wf_name,d.wf_desc,d.wf_type,d.date_created,d.crt_user_code,d.date_startup,")
		   .append("d.date_completed,d.wf_instance_num,d.startUp_role_id,d.form_id,d.proc_id,d.id,b.full_name ")
		   .append("from dc_workflow_table d left join base_user b on d.crt_user_code = b.user_code where d.id = ?");
		QueryOperator query = new QueryOperator();
		query.setSql(sql.toString());
		query.addParameter(new SqlParameter(SqlType.VARCHAR,id));
		query.access();
		if(query.resultSetAvailable()) {//检查结果集是否可用
			//获取并处理记录集
			RsDataSet rs = new RsDataSet(query.getSqlResultSet());
			if(rs.rowCount > 0) {
				ct.setId(rs.getFieldValueAsString("id"));
				ct.setName(rs.getFieldValueAsString("wf_name"));
				ct.setDescription(rs.getFieldValueAsString("wf_desc"));
				ct.setType(rs.getFieldValueAsInteger("wf_type").intValue());
				ct.setCreateDate(rs.getFieldValueAsDate("date_created"));
				ct.setCrtUserCode(rs.getFieldValueAsString("crt_user_code"));
				ct.setStartupDate(rs.getFieldValueAsDate("date_startup"));
				ct.setCompletedDate(rs.getFieldValueAsDate("date_completed"));
				ct.setInstanceNum(rs.getFieldValueAsInteger("wf_instance_num").intValue());
				ct.setStartUpRole(rs.getFieldValueAsString("startUp_role_id"));
				ct.setFormId(rs.getFieldValueAsString("form_id"));
				ct.setProcId(rs.getFieldValueAsString("proc_id"));
				ct.setCrtUserName(rs.getFieldValueAsString("full_name"));
			}
			rs.clearAll();
		}
		return ct;
	}

	public List getCollectionTasks() {
		logger.debug(Constants.INTOMETHOD + "getCollectionTasks");
		StringBuffer sqlStr = new StringBuffer();
		sqlStr.append("select d.wf_name,d.wf_desc,d.wf_type,d.date_created,d.crt_user_code,d.date_startup,")
		   .append("d.date_completed,d.wf_instance_num,d.startUp_role_id,d.form_id,d.proc_id,d.id,b.full_name,t.item_name, ")
		   .append("f.form_name from dc_workflow_table d left join base_user b on d.crt_user_code = b.user_code ")
		   .append(" left join dc_item_info t on d.proc_id = t.id left join dc_collection_form f ")
		   .append(" on d.form_id = f.id ");
		QueryParameters params = new QueryParameters();
	
		String sql = sqlStr.toString();
		List list = null;
		try {
			list = this.list(sql, params, "getCTJO");
		} catch (Exception e) {
			logger.error("getCollectionTasks:" + Constants.SEARCH
					+ "CollectionTasks" + Constants.FAIL,e);
			throw new SystemException("search db record error!");
		}
		logger.debug("getCollectionTasks" + Constants.SEARCH + "CollectionTasks"
				+ Constants.SUCCESS);
		return list;
	
	}
	
	public final CollectionTaskJSONObject getCTJO(ResultSet rs) throws SQLException {
		CollectionTaskJSONObject ctjo = new CollectionTaskJSONObject();
		ctjo.setId(rs.getString("id"));
		ctjo.setName(rs.getString("wf_name"));
		ctjo.setDescription(rs.getString("wf_desc"));
		ctjo.setType(rs.getInt("wf_type"));
		String crtDateStr = Format.getInstance().dateToYMD(rs.getDate("date_created"));
		ctjo.setCreateDateStr(crtDateStr);
		ctjo.setCrtUserCode(rs.getString("crt_user_code"));
		String startupDate = Format.getInstance().dateToYMD(rs.getDate("date_startup"));
		ctjo.setStartupDateStr(startupDate);
		String completedDate = Format.getInstance().dateToYMD(rs.getDate("date_completed"));
		ctjo.setCompletedDateStr(completedDate);
		ctjo.setInstanceNum(rs.getInt("wf_instance_num"));
		ctjo.setStartUpRole(rs.getString("startUp_role_id"));
		ctjo.setFormId(rs.getString("form_id"));
		ctjo.setProcId(rs.getString("proc_id"));
		ctjo.setCrtUserName(rs.getString("full_name"));
		ctjo.setProcName(rs.getString("item_name"));
		ctjo.setFormName(rs.getString("form_name"));
		
		return ctjo;
	}

	/**
	 * 修改任务实例个数
	 * @return
	 * @throws DaoException
	 */
	public boolean updateTaskInstanceNum(String id) throws DaoException {
		logger.debug(Constants.INTOMETHOD + "getCollectionTasks");
		String sql = "update dc_workflow_table set wf_instance_num = wfInstanceNum.NEXTVAL where id=?";
		UpdateOperator update = new UpdateOperator();
		update.setSql(sql);
		update.addParameter(new SqlParameter(SqlType.VARCHAR,id));
		try{
			update.access();
		}catch(Exception e){
			logger.error("更新任务实例个数出错！", e);
			throw new DaoException("更新任务实例个数出错！");
		}

		int effectCount = update.getEffectCounts();
		if(effectCount > 0) {
			
			if (logger.isDebugEnabled()) {
				logger.debug("save:" + Constants.UPDATE + "任务实例个数"
						+ Constants.SUCCESS);
			}
			return true;
		}else{
			if (logger.isDebugEnabled()) {
				logger.debug("save:" + Constants.UPDATE + "任务实例个数"
						+ Constants.FAIL);
			}
			return false;
		}
	}

}
